package org.xmx0632.connector.codec;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xmx0632.connector.protocol.JsonMessageParser;
import org.xmx0632.connector.protocol.message.BaseMessage;
import org.xmx0632.connector.protocol.message.InvalidRequest;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

/**
 * 处理从客户端接收到的JSON串,根据其中的标识符,转换为对应的Java Message Object
 * 
 * String->Message Object
 * 
 */
@Component
@Sharable
public class JsonMessageDecoder extends MessageToMessageDecoder<String> {

	private static final Logger LOG = LoggerFactory.getLogger(JsonMessageDecoder.class);

	@Autowired
	private JsonMessageParser jsonMessageParser;

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		LOG.debug("channelReadComplete");
		ctx.flush();
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception {
		BaseMessage message = jsonMessageParser.parse(msg);
		LOG.debug("message:{}", message);
		if (message instanceof InvalidRequest) {
			// TODO 解析消息错误,断开客户端连接
			LOG.error("invalid request:{}", message);
			ctx.close();
			return;
		}
		// !!!注入客户端连接信息!!!
		message.setRemoteAddress(ctx.channel().remoteAddress().toString());
		out.add(message);
	}

	public JsonMessageParser getJsonMessageParser() {
		return jsonMessageParser;
	}

	public void setJsonMessageParser(JsonMessageParser jsonMessageParser) {
		this.jsonMessageParser = jsonMessageParser;
	}

}
